package com.aos.iot.protocol.hll.util;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CodeUtil {

    /**
     * 16进制数据切块
     * @param hex
     * @return
     */
    public static List<String> blocks(String hex) {
        List<String> blockList = new ArrayList<>();
        int blockNum = hex.length() / 2;
        for(int i = 0; i < blockNum; i++) {
            blockList.add(StrUtil.sub(hex, i*2, (i+1)*2));
        }
        return blockList;
    }

    /**
     * 16进制数据反转
     * @param hex
     * @return
     */
    public static String highRotation(String hex) {
        List<String> blockList = blocks(hex);
        Collections.reverse(blockList);
        return StrUtil.join("", blockList);
    }

    /**
     * 数据签名
     * @return
     */
    public static String sign(String version, String encrypt, String length, String sn, String cmd, String dataContext) {
        String hex = StrUtil.join("", version, encrypt, length, sn, cmd, dataContext);
        int sum = 0;
        List<String> blockList = blocks(hex);
        for(String block : blockList) {
            sum += HexUtil.hexToInt(block);
        }
        return String.format("%02x", sum % 256);
    }

}
